import {login, logout, getInfo, loginAgent, loginStore} from '@/api/user'
import {getToken, setToken, removeToken} from '@/utils/auth'
import { asyncRoutes, constantRoutes, resetRouter } from '@/router'

function hasPermission(roles, route) {

    if (route.meta && route.meta.roles) {
        return roles.some(role => route.meta.roles.includes(role))
    } else {
        return true
    }

}

export function filterAsyncRoutes(routes, roles) {
    const res = []

    routes.forEach(route => {
        const tmp = {...route}

        if (hasPermission(roles, tmp)) {

            if (tmp.children) {
                tmp.children = filterAsyncRoutes(tmp.children, roles)
            }
            res.push(tmp)
        }
    })

    return res
}

const state = {
    routes: [],
    addRoutes: [],
    token: getToken(),
    name: '',
    avatar: '',
    roles: []
}

const mutations = {
    SET_TOKEN: (state, token) => {
        state.token = token
    },
    SET_NAME: (state, name) => {
        state.name = name
    },
    SET_AVATAR: (state, avatar) => {
        state.avatar = avatar
    },
    SET_STORE: (state, store) => {
        state.store = store
    },
    SET_ROUTES: (state, routes) => {
        state.addRoutes = routes
        state.routes = constantRoutes.concat(routes)
    },
    SET_ROLES: (state, roles) => {
        state.roles = roles
    }
}

const actions = {
    generateRoutes({commit}, rules) {
        return new Promise(resolve => {
            let accessedRoutes
            accessedRoutes = filterAsyncRoutes(asyncRoutes, rules);
            commit('SET_ROUTES', accessedRoutes)
            resolve(accessedRoutes)
        })
    },
    // user login
    login({commit}, userInfo) {
        console.log(userInfo)
        const {username, password} = userInfo
        return new Promise((resolve, reject) => {
            login({username: username.trim(), password: password}).then(response => {
                if (response.status === 'failed') {
                    resolve(response);
                    return;
                }
                const {data} = response

                localStorage.setItem('user_store_id', ''); //商户ID
                localStorage.setItem('user_id', '');      //代理ID
                localStorage.setItem('user_name', data.username);
                localStorage.setItem('user_avatar', data.avatar);
                commit('SET_TOKEN', data.token);
                commit('SET_STORE', null);
                commit('SET_NAME', data.username);
                commit('SET_AVATAR', data.avatar);
                commit('SET_ROLES', []);

                setToken(data.token)
                resolve(response)
            }).catch(error => {
                console.log(error)
                reject(error)
            })
        })
    },

    loginAgent({commit}, userInfo) {
        const {username, password} = userInfo
        return new Promise((resolve, reject) => {
            loginAgent({username: username, password: password}).then(response => {
                if (response.status === 'failed') {
                    resolve(response);
                    return;
                }
                const {data} = response;


                console.log(data);

                localStorage.setItem('user_store_id', ''); //商户ID
                localStorage.setItem('user_id', data.id);   //代理ID
                localStorage.setItem('user_name', data.username);
                localStorage.setItem('user_avatar', data.avatar);
                commit('SET_STORE', null);
                commit('SET_NAME', data.username);
                commit('SET_AVATAR', data.avatar);
                commit('SET_TOKEN', data.token);

                setToken(data.token)
                resolve(response)
            }).catch(error => {
                reject(error)
            })
        })
    },

    loginStore({commit}, userInfo) {
        const {username, password} = userInfo
        return new Promise((resolve, reject) => {
            loginStore({username: username, password: password}).then(response => {
                if (response.status === 'failed') {
                    resolve(response);
                    return;
                }
                const {data} = response;


                console.log(data);

                localStorage.setItem('user_id', '');   //代理ID
                localStorage.setItem('user_store_id', data.id);  //商户ID
                localStorage.setItem('user_name', data.name);
                localStorage.setItem('user_avatar', data.avatar);
                commit('SET_TOKEN', data.token);
                commit('SET_STORE', data.id);
                commit('SET_NAME', data.name);
                commit('SET_AVATAR', data.avatar);

                setToken(data.token)
                resolve(response)
            }).catch(error => {
                reject(error)
            })
        })
    },

    // get user info
    getInfo({commit, state}) {
        const agent_id = localStorage.getItem('user_id');
        const store_id = localStorage.getItem('user_store_id');
        const type = [];
        commit('SET_NAME', localStorage.getItem('user_name'))
        commit('SET_AVATAR', localStorage.getItem('user_avatar'))
        return new Promise((resolve, reject) => {
            if (agent_id === '' && store_id === ''){
                type.push('admin');
            }

            if (agent_id !== '' && store_id === ''){
                type.push('agent');
            }

            if (agent_id === '' && store_id !== ''){
                type.push('store');
            }

            commit('SET_ROLES', type)
            resolve(type)
        })
    },

    // user logout
    logout({commit, state}) {
        return new Promise((resolve, reject) => {
            commit('SET_TOKEN', '');
            commit('SET_STORE', '');
            commit('SET_NAME', '');
            commit('SET_AVATAR', '');
            commit('SET_ROLES', []);
            localStorage.removeItem('user_name');
            localStorage.removeItem('user_avatar');
            localStorage.removeItem('user_id');
            localStorage.removeItem('user_store_id');
            removeToken();

            resolve()
//       logout(state.token).then(() => {
//         commit('SET_TOKEN', '')
//         removeToken()
//         resetRouter()
//         resolve()
//       }).catch(error => {
//         reject(error)
//       })
        })
    },

    // remove token
    resetToken({commit}) {
        console.log('opopopop')
        return new Promise(resolve => {
            commit('SET_TOKEN', '')
            commit('SET_NAME', '')
            commit('SET_AVATAR', '')
            localStorage.removeItem('user_name')
            localStorage.removeItem('user_avatar')
            removeToken()
            resolve()
        })
    }
}


export default {
    namespaced: true,
    state,
    mutations,
    actions
}

